
import { readdirSync, readFileSync } from 'node:fs'
import { fileURLToPath } from 'url'
import path from 'path'
import type { IColumn } from "./typings/index";

export const resolve = (pathName:string) => {
  return path.resolve(path.dirname(fileURLToPath(import.meta.url)), pathName)
}

/**
 * 读取JSON文件
 * @param {string} fileDirPath 
 * @returns 
 */
export function getFieldsJSONFile(fileDirPath) {
  const jsonFile = readdirSync(resolve(fileDirPath))
  const updateColumns = jsonFile.map(file => {
    const data  = readFileSync(`${fileDirPath}/${file}`)
    const groupData = data.toString()
    
    const res = /^(\w+)\.json$/.exec(file)?.[1] as string
    
    const isCustomData = file.includes('CoreIndex')
    const [ column, defaultFlag ] = res.split('_')
    return {
      fileName: file,
      column,
      dataType: defaultFlag ? 2 : 1,
      groupData,
      columnType: isCustomData ? '自定义数据' : '自定义列'
    }
  })
  return updateColumns
}


/**
 * 检测是否存在重复的key
 */
export function checkDuplicateKeys(arr: Array<IColumn>, fileName:string) {
  const keys = arr.map((i) => i.dataIndex);

  // 查找出现次数大于1的key
  const duplicateKeys = keys.filter((item, index) => keys.indexOf(item) !== index);
  if (duplicateKeys.length) {
    console.log(
      `存在重复的key: ${Array.from(new Set(duplicateKeys))}; 数量${duplicateKeys.length
      }个, 文件名: ${fileName}`
    );
    return duplicateKeys;
  }
  return [];
}

/**
 * 移除字符串中的双引号
 * @param str 
 * @returns {string}
 */
export const removeQuotes = (str:string) => str.replace(/"|'/g, '');